package questions;

import org.junit.jupiter.api.Test;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

public class HashMapNotSafe {
    //多线程出错的例子
    @Test
    public void testHashMapIssue(){
        Map<String,String> map =new HashMap<>();
        for (int i = 0; i <10; i++) {
            new Thread(()->{
                map.put(Thread.currentThread().getName(),UUID.randomUUID().toString());
                System.out.println(map);
            },String.valueOf(i)).start();
        }
        while (Thread.activeCount()>2){
            //让出时间片，大家再去抢
            Thread.yield();
        }
        System.out.println(map);
        System.out.println(map.size());
    }
    /************concurrentHashMap*****************/
    @Test
    public void testConcurrentHashMap(){
        Map<String,String> map =new ConcurrentHashMap<>();
        for (int i = 0; i <10; i++) {
            new Thread(()->{
                map.put(Thread.currentThread().getName(),UUID.randomUUID().toString());
                System.out.println(map);
            },String.valueOf(i)).start();
        }
        while (Thread.activeCount()>2){
            //让出时间片，大家再去抢
            Thread.yield();
        }
        System.out.println(map);
        System.out.println(map.size());
    }
}
